#include <tcInput/tc_input.h>
#include <tcDatabase/tc_chessboard.h>
#include <tcPhysics/tc_physics.h>
#include <tcLogic/tc_logic.h>

#pragma warning(disable: 4244)

static float g_target_dist = 0;
static float g_target_angle = 0;

static BOOL point_in_circle(tc_vector2 point, tc_vector2 center, float radius)
{
	return tc_vector2_dist(point, center) < radius;
}

BOOL tc_input_mouse_down( tc_vector2 location )
{
	tc_vector2 position;
	float radius = 0;
	BOOL ret = false;
	int id = 0;

	for (; id < TC_CHESSMEN_MAX_NUMBER; id++)
	{
		float radius = tc_chessman_get_radius(id);
		tc_chessman_get_position(id, &position);
		if (point_in_circle(location, position, radius))
		{
			if (!tc_logic_get_chessman_valid(id))
			{
				return false;
			}
			ret = tc_logic_select_chessman(id);
			break;
		}
	}
	return ret;
}

void tc_input_mouse_move( tc_vector2 location )
{
	float dist = 0;
	tc_vector2 position;
	float angle = 0;
	int selected_chessman;
	selected_chessman = tc_logic_get_selected_chessman();
	
	if (selected_chessman != TC_CHESSMAN_NULL)
	{
		tc_chessman_get_position(selected_chessman, &position);
		dist = tc_vector2_dist(location, position);

		if( location.x >= position.x ) 
		{
			angle = 180 + acos((location.y - position.y)/dist)/M_PI*180;
		}
		else 
		{
			angle = 180 - acos((location.y - position.y)/dist)/M_PI*180;
		}

		g_target_angle = angle;
		tc_clampf(&dist, 0, TC_TARGET_MAX_DIST);
		g_target_dist = dist;
	}
}

void tc_input_mouse_up( tc_vector2 location )
{
	float speed = 0;
	tc_vector2 impulse;
	float speed_factors[] = {1.6f/20*45, 1.3f/20*45, 0.63f/20*45};
	tcType size;
	int selected_chessman;
	selected_chessman = tc_logic_get_selected_chessman();

	if (selected_chessman != TC_CHESSMAN_NULL)
	{
		tc_clampf(&g_target_dist, TC_TARGET_MIN_DIST, TC_TARGET_MAX_DIST);
		speed = g_target_dist - TC_TARGET_MIN_DIST;

		if (tc_logic_get_game_state() == TC_GS_USING_POWERUP_PROP)
		{
			speed *= 1.4;
		}

		size = tc_chessman_get_size(selected_chessman);
		speed *= speed_factors[size];

		impulse.x = speed*sin(g_target_angle/180*M_PI);
		impulse.y = speed*cos(g_target_angle/180*M_PI);

		tc_logic_shoot_chessman(selected_chessman, impulse);

		tc_logic_select_chessman(TC_CHESSMAN_NULL);

		g_target_angle = 0;
		g_target_dist = 0;
	}
}

float tc_input_get_target_dist()
{
	return g_target_dist;
}

float tc_input_get_target_angle()
{
	return g_target_angle;
}


